using MultiAgentsClient.ChatDataStructures;
using MultiAgentsClient.Service.WorkflowEngine.BaseNodes;
using MultiAgentsClient.Service.WorkflowEngine.BuiltInNodes;
using Newtonsoft.Json;

namespace MultiAgentsClient.Service.WorkflowEngine;

/// <summary>
/// Only Nodes and connections would be serialized to ensure the simplicity of workflowJson
/// </summary>
public class BehaviorTreeConfig
{
    public enum WorkflowType
    {
        None = 0,
        ManualTriggerWorkflow = 1,
        EventTriggerWorkflow = 2,
    }

    [JsonIgnore] public int workflowId;
    [JsonIgnore] public int ownerId;
    [JsonIgnore] public string name;
    public BaseNode TriggerNode;
    public List<BaseNode> OperationNodes;
    public List<WorkflowConnection> connections;
    public string configJson;

    [JsonIgnore]
    public WorkflowType workflowType
    {
        get
        {
            if (TriggerNode is UserInputNode)
            {
                return WorkflowType.ManualTriggerWorkflow;
            }
            else if (TriggerNode is GitlabNode)
            {
                return WorkflowType.EventTriggerWorkflow;
            }
            else
            {
                return WorkflowType.None;
            }
        }
    }

    public BehaviorTreeConfig(int workflowId, int ownerId, string name, string workflowConfigJson)
    {
        this.workflowId = workflowId;
        this.ownerId = ownerId;
        this.name = name;
        this.configJson = workflowConfigJson;

        this.FromJson(workflowConfigJson);
    }

    public BehaviorTreeConfig(int workflowId, int ownerId, string name)
    {
        this.workflowId = workflowId;
        this.ownerId = ownerId;
        this.name = name;

        TriggerNode = null;
        OperationNodes = [];
        connections = [];
    }

    public WorkflowDisp ToDisp()
    {
        return new WorkflowDisp(workflowId, name, false);
    }

    /// <summary>
    /// This would only copy nodes and connections
    /// </summary>
    /// <param name="toConfig"></param>
    public static BehaviorTreeConfig MakeNewCopyFromJson(int workflowId, int ownerId, string name, string workflowConfigJson)
    {
        var toConfig = new BehaviorTreeConfig(workflowId, ownerId, name, workflowConfigJson);

        return toConfig;
    }

    public static string EmptyTemplate()
    {
        return "{\r\n  \"WorkflowName\": \"New Workflow\",\r\n  \"TriggerNode\": {},\r\n  \"OperationNodes\": [],\r\n  \"Connections\": []\r\n}";
    }
}
